﻿using System;
using UnityEngine;
using UnityEditor;
using System.IO;

public static class EditorHelper
{
    public static string DirectoryField(string label, string directory, string rootDir = "")
    {
        bool oldChanged = GUI.changed;
        GUILayout.BeginHorizontal();
        {
            EditorGUILayout.PrefixLabel(label);
            if (GUILayout.Button(string.IsNullOrEmpty(directory) ? "Click to select directory" : directory))
            {
                string fullDir = string.IsNullOrEmpty(rootDir) ? directory : rootDir + "/" + directory;
                string newDir = EditorUtility.OpenFolderPanel("Select Directory", fullDir, "");
                if (!string.IsNullOrEmpty(newDir))
                {
                    if (!string.IsNullOrEmpty(rootDir))
                        newDir = newDir.Substring(rootDir.Length + 1);
                    if (directory != newDir)
                        directory = newDir;
                    else
                        GUI.changed = oldChanged;
                }
                else
                    GUI.changed = oldChanged;
            }
        }
        GUILayout.EndHorizontal();

        return directory;
    }

    /// <summary>
    //	This makes it easy to create, name and place unique new ScriptableObject asset files.
    /// </summary>
    public static void CreateAsset<T>() where T : ScriptableObject
    {
        T asset = ScriptableObject.CreateInstance<T>();

        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (path == "")
        {
            path = "Assets";
        }
        else if (Path.GetExtension(path) != "")
        {
            path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
        }

        string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/New " + typeof(T).ToString() + ".asset");

        AssetDatabase.CreateAsset(asset, assetPathAndName);

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        EditorUtility.FocusProjectWindow();
        Selection.activeObject = asset;
    }
}